#include "RealtimeData.h"
#include "ui_RealtimeData.h"
#include "Tools/MqttClient.h"
#include "Tools/MyUrl.h"

#include <QtMqtt/QMqttClient>
#include <QtMqtt/QMqttTopicName>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

RealtimeData::RealtimeData(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RealtimeData)
{
    ui->setupUi(this);

    this->comBoxDeviceInit();
    this->chart_temperature_init();

    connect(&MqttClient::getInstance(), &MqttClient::data_recived, this, [=](QJsonObject newData){
        if(newData["device_id"] == this->ui->comboBox_device->currentText())
        {
            this->series_temperature->append(QDateTime::currentMSecsSinceEpoch(), newData["data"].toDouble());
        }

        this->axisX_temperature->setRange(QDateTime::currentDateTime().addSecs(-50), QDateTime::currentDateTime());
    });
}

void RealtimeData::comBoxDeviceInit()
{
    QNetworkAccessManager* manager = new QNetworkAccessManager();
    connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply *reply){
        QJsonParseError parseError;
        QJsonDocument jsonData = QJsonDocument::fromJson(reply->readAll(), &parseError);

        if (parseError.error != QJsonParseError::NoError)
        {
            qDebug() << "JSON 解析失败：" << parseError.errorString() << __LINE__ << __FILE_NAME__;
            return;
        }

        QJsonArray deviceArray = jsonData.array();

        for(const QJsonValue &value: deviceArray)
        {
            QJsonObject deviceJson = value.toObject();
            this->ui->comboBox_device->addItem(deviceJson["device_id"].toString());
        }
    });
    QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::deviceSelect));
    request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    manager->get(*request);
}

RealtimeData::~RealtimeData()
{
    delete ui;
}

void RealtimeData::chart_temperature_init()
{
    // 布局初始化
    this->layout_temperature = new QVBoxLayout();
    this->ui->widget_temperature->setLayout(this->layout_temperature);
    this->ui->widget_temperature->setContentsMargins(0, 0, 0, 0);

    // 曲线系列设置
    this->series_temperature = new QLineSeries();
    this->series_temperature->setUseOpenGL(true);

    this->series_temperature->setName("实时数据变化曲线");
    this->series_temperature->setPen(QPen(QColor(59, 130, 246), 2)); // 淡蓝色曲线
    this->series_temperature->setPointsVisible(true);
    this->series_temperature->setPointLabelsVisible(false);

    // 区域填充
    QAreaSeries *areaSeries = new QAreaSeries(series_temperature);
    areaSeries->setUseOpenGL(true);

    // 淡蓝渐变
    QLinearGradient gradient(QPointF(0, 0), QPointF(0, 1));
    gradient.setColorAt(0, QColor(59, 130, 246, 100)); // 上半透明淡蓝
    gradient.setColorAt(1, QColor(59, 130, 246, 10));  // 下部几乎透明
    gradient.setCoordinateMode(QGradient::ObjectBoundingMode);

    areaSeries->setBrush(gradient);
    areaSeries->setPen(QPen(Qt::NoPen)); // 边界线隐藏


    // 图表设置
    this->chart_temperature = new QChart();
    this->chart_temperature->addSeries(areaSeries); // 添加填充区域系列
    this->chart_temperature->addSeries(series_temperature); // 添加线系列（在区域上方）
    this->chart_temperature->setTitle("实时数据监测折线图");

    // 美化标题
    QFont titleFont = chart_temperature->titleFont();
    titleFont.setBold(true);
    titleFont.setPointSize(12);
    titleFont.setFamily("微软雅黑 UI");
    chart_temperature->setTitleFont(titleFont);
    chart_temperature->setTitleBrush(QBrush(QColor(60, 60, 60))); // 深灰色标题

    // 设置动画效果
    this->chart_temperature->setAnimationOptions(QChart::SeriesAnimations);
    this->chart_temperature->setAnimationDuration(1000); // 动画持续时间1秒

    // X轴（时间轴）设置
    this->axisX_temperature = new QDateTimeAxis();
    this->axisX_temperature->setTitleText("时间");
    this->axisX_temperature->setFormat("HH:mm:ss");
    this->axisX_temperature->setRange(QDateTime::currentDateTime().addSecs(-300),
                                      QDateTime::currentDateTime());
    this->axisX_temperature->setTickCount(6); // 6个刻度
    this->axisX_temperature->setGridLineVisible(true);
    this->axisX_temperature->setGridLinePen(QPen(QColor(220, 220, 220), 1, Qt::DotLine));
    this->axisX_temperature->setLabelsFont(QFont("微软雅黑 UI", 9)); // 设置字体，支持中文

    // Y轴（温度轴）设置
    this->axisY = new QValueAxis();
    this->axisY->setTitleText("数值");
    this->axisY->setRange(10, 40); // y轴范围
    this->axisY->setTickCount(7);  // 刻度数量
    this->axisY->setGridLineVisible(true);
    this->axisY->setGridLinePen(QPen(QColor(220, 220, 220), 1, Qt::DotLine));
    this->axisY->setLabelsFont(QFont("微软雅黑 UI", 9)); // 设置字体，支持中文
    this->axisY->setTitleBrush(QBrush(QColor(80, 80, 80))); // 轴标题颜色

    // 添加坐标轴
    this->chart_temperature->addAxis(this->axisX_temperature, Qt::AlignBottom);
    this->series_temperature->attachAxis(this->axisX_temperature);
    areaSeries->attachAxis(this->axisX_temperature);

    this->chart_temperature->addAxis(axisY, Qt::AlignLeft);
    this->series_temperature->attachAxis(axisY);
    areaSeries->attachAxis(axisY);

    // 图例设置
    chart_temperature->legend()->setVisible(true);
    chart_temperature->legend()->setAlignment(Qt::AlignTop);
    chart_temperature->legend()->setFont(QFont("微软雅黑 UI", 10));

    // 图表视图设置
    this->chartView_temperature = new QChartView(this->chart_temperature);
    this->chartView_temperature->setRenderHint(QPainter::Antialiasing);

    // 设置图表背景
    chartView_temperature->setBackgroundBrush(QBrush(QColor(255, 255, 255)));
    chart_temperature->setBackgroundBrush(QBrush(QColor(255, 255, 255)));

    // 添加边框
    //chartView_temperature->setStyleSheet("border: 1px solid #e0e0e0; border-radius: 4px;");

    // 添加到布局
    this->layout_temperature->addWidget(this->chartView_temperature);

    // 添加数据提示（悬停时显示数值）
    QToolTip::setFont(QFont("微软雅黑 UI", 10));
    connect(series_temperature, &QLineSeries::hovered,
            this, [=](const QPointF &point, bool state) {
                if (state) {
                    QDateTime time = QDateTime::fromMSecsSinceEpoch(point.x());
                    QString tooltip = QString("%1\n数值: %2")
                                          .arg(time.toString("HH:mm:ss"))
                                          .arg(point.y(), 0, 'f', 1);
                    QToolTip::showText(QCursor::pos(), tooltip);
                }
            });
}


void RealtimeData::on_comboBox_device_currentTextChanged(const QString &arg1)
{
    this->series_temperature->clear();
    if(arg1 == "TemperatureSensor")
    {
        this->axisY->setRange(20, 40);
    }
    else if(arg1 == "HumiditySensor")
    {
        this->axisY->setRange(0, 100);
    }
}

